# coding: utf-8

import sys, os

if sys.getdefaultencoding() != 'utf-8':
    reload(sys)
    sys.setdefaultencoding('utf-8')

sys.path.insert(0, '.')

    
from twisted.python import log
from twisted.application import service, internet
from twisted.internet import defer

import txmongo
import cyclone.web
from cyclone.web import Application
from webhelpers.paginate import Page, PageURL

from settings import settings
from db import code_db, coupon_db

from datetime import datetime

from utils.url_shorten import encode_url, decode_url

class IndexHandler(cyclone.web.RequestHandler):
    def get(self):
        self.render('index.html')

    @defer.inlineCallbacks
    def post(self):
        uid = self.get_argument('code', default='', strip=True)
        name = self.get_argument('tb_name', default='', strip=True)
        
        uid = uid.replace('优惠码', '')
        name = name.replace('淘宝账号', '')
        
        err_msg = ''
        if uid and name:
            item = yield code_db.find_one({'uid':uid})
            now = datetime.utcnow()   
            
            if item and (item.get('applied') == False) and ( (item.get('valid') - now).days >= 0):
                item['applied'] = True
                item['applied_date'] = now
                item['tb_name'] = name
                yield code_db.save(item)
                
                self.redirect(item['url'])
                return;
            else:
                if not item:
                    err_msg = '您输入的优惠码无效。'
            
                else:
                    if item.get('applied'):
                        err_msg = '您输入的优惠码已经被使用。'
                    
                    if item.get('valid') < now:
                        err_msg = '您输入的优惠码已经过期。'

        else:
            err_msg = '请您输入淘宝账户名称和优惠码.'
        
        self.render('index.html', err_msg=err_msg, tb_name=name, uid=uid)

class LoginHandler(cyclone.web.RequestHandler):
    def get(self):
        self.render('new/login.html')
        
    def post(self):
        user = self.get_argument('username', default='', strip=True)
        password = self.get_argument('password', default='', strip=True)
        
        if user=='table' and password=='kick':
            self.redirect('/home/')
                
        self.redirect('/table/')


class CouponHandler(cyclone.web.RequestHandler):
    
    @defer.inlineCallbacks
    def get(self):
        f = txmongo.filter.sort(txmongo.filter.DESCENDING('created'))
        coupons = yield coupon_db.find(filter=f)
        self.render('new/list.html', coupons=coupons)

class CouponCreateHandler(cyclone.web.RequestHandler):
    
    def get(self):
        self.render('new/home.html', )
    
    
    @defer.inlineCallbacks
    def post(self):
        url = self.get_argument('url', default='', strip=True)
        name = self.get_argument('name', default='', strip=True)
        amount = self.get_argument('amount', default=10)
        number = self.get_argument('number', default=100)
        valid = self.get_argument('valid-date', default='', strip=True)
        desc = self.get_argument('desc', default='', strip=True)
        count = yield coupon_db.count()
        data = {
            'uid':int(count),
            'url':url,
            'name':name,
            'amount':int(amount),
            'number':int(number),
            'valid':datetime.strptime(valid,'%Y/%m/%d'),
            'desc':desc,
            'created': datetime.utcnow(),
            'updated': datetime.utcnow(),
        }
        
        if url and valid :   
            #check if this url exist
            coupon = yield coupon_db.find_one({'url':url}) 
            if not coupon:
                yield coupon_db.save(data)
                
                count = yield code_db.count({})
                #insert code.
                
                for i in range(data['number']):

                    code = {
                        'number': int(count)+i,
                        'uid':encode_url(int(count)+i, 6),
                        'coupon': data['uid'],
                        'url':data['url'],
                        'created': datetime.utcnow(),
                        'valid':data['valid'],
                        'applied': False,
                    }
                    yield code_db.save(code)
                
                self.redirect('/coupon/')
        
        self.redirect('/home/')

class CouponViewHandler(cyclone.web.RequestHandler):
    
    @defer.inlineCallbacks
    def get(self, uid):
        uid = int(uid)
        coupon = yield coupon_db.find_one({'uid':uid})
        
        page_num = self.get_argument('page', default=1, strip=True)
        try:
            page_num = int(page_num)
        except:
            page_num = 1
        
        t = self.get_argument('t', default='0', strip=True)
        
        applied = (t == '0')
        count = yield code_db.count({'coupon':uid, 'applied':applied})
        url_for_page = PageURL('/coupon/view/'+str(uid)+'/', {'t':t, 'page':1})
        page = Page(range(1, int(count)+1), page=page_num, items_per_page=50 ,url=url_for_page)
        
        codes = yield code_db.find({'coupon':uid, 'applied':applied}, skip=((page_num-1)*50), limit=50)
        
        self.render('new/view.html', coupon=coupon, codes=codes, t=t, page=page)


webapp = Application([
    (r"/$", IndexHandler),
    (r"/table/$", LoginHandler),
    (r"/coupon/$", CouponHandler),
    (r"/home/$", CouponCreateHandler),
    (r"/coupon/view/(\w*)/", CouponViewHandler),
    ], **settings)

application = service.Application("go.ide.fm")

pinpinService = internet.TCPServer(8081, webapp, interface="localhost")
pinpinService.setServiceParent(application)
